# -*- coding: utf-8 -*-
from viapi.fileutils import FileUtils
from Tea.exceptions import TeaException
from alibabacloud_facebody20191230.client import Client as facebody20191230Client
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_facebody20191230 import models as facebody_20191230_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_tea_util.client import Client as UtilClient

# import json as js
from enum import Enum

from Config import getConfig


class operate(Enum):
    Create = 1
    Delete = 0


class Sample:
    def __init__(self):
        pass

    @staticmethod
    def create_client(
            access_key_id: str,
            access_key_secret: str,
    ) -> facebody20191230Client:
        """
        使用AK&SK初始化账号Client
        @param access_key_id:
        @param access_key_secret:
        @return: Client
        @throws Exception
        """
        config = open_api_models.Config(
            # 必填，您的 AccessKey ID,
            access_key_id=access_key_id,
            # 必填，您的 AccessKey Secret,
            access_key_secret=access_key_secret
        )
        # 访问的域名
        config.endpoint = f'facebody.cn-shanghai.aliyuncs.com'
        return facebody20191230Client(config)

    @staticmethod
    def CreateDelete_Face_Db(name, db_operate: operate):
        ru = 0
        client = Sample.create_client(getConfig("client.config", 'aliyun', 'AccessKeyID'),
                                      getConfig("client.config", 'aliyun', 'AccessKeySecret'))
        create_face_db_request = facebody_20191230_models.CreateFaceDbRequest(name)
        runtime = util_models.RuntimeOptions()
        try:
            if db_operate == operate.Create:
                ru = client.create_face_db_with_options(create_face_db_request, runtime).status_code
            elif db_operate == operate.Delete:
                ru = client.delete_face_db_with_options(create_face_db_request, runtime).status_code
        except Exception as error:
            # 如有需要，请打印 error
            ru = UtilClient.assert_as_string(error)
        return ru

    @staticmethod
    def ListFaceDbs():
        client = Sample.create_client(getConfig("client.config", 'aliyun', 'AccessKeyID'),
                                      getConfig("client.config", 'aliyun', 'AccessKeySecret'))
        list_face_dbs_request = facebody_20191230_models.ListFaceDbsRequest()
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            ru = client.list_face_dbs_with_options(list_face_dbs_request, runtime).body.data.to_map()['DbList']

        except Exception as error:
            # 如有需要，请打印 error
            ru = UtilClient.assert_as_string(error)
        return ru

    @staticmethod
    def AddDeleteFace_Entity(db_name, entity_id, labels='学生', entity_operate: operate = operate.Create):
        ru = 0
        client = Sample.create_client(getConfig("client.config", 'aliyun', 'AccessKeyID'),
                                      getConfig("client.config", 'aliyun', 'AccessKeySecret'))
        face_entity_request = facebody_20191230_models.AddFaceEntityRequest(db_name, entity_id, labels)
        runtime = util_models.RuntimeOptions()
        try:
            if entity_operate == operate.Create:
                ru = client.add_face_entity_with_options(face_entity_request, runtime).status_code
            elif entity_operate == operate.Delete:
                ru = client.delete_face_entity_with_options(face_entity_request, runtime).status_code
        except Exception as error:
            ru = UtilClient.assert_as_string(error)
        return ru

    @staticmethod
    def AddFace(db_name, image_path, entity_id):
        try:
            client = Sample.create_client(getConfig("client.config", 'aliyun', 'AccessKeyID'),
                                          getConfig("client.config", 'aliyun', 'AccessKeySecret'))
            file_utils = FileUtils(getConfig("client.config", 'aliyun', 'AccessKeyID'),
                                   getConfig("client.config", 'aliyun', 'AccessKeySecret'))
            oss_url = file_utils.get_oss_url(image_path, "png", True)
            # print(oss_url)
            add_face_request = facebody_20191230_models.AddFaceRequest(db_name=db_name, image_url=oss_url,
                                                                       entity_id=entity_id)
            runtime = util_models.RuntimeOptions()

            ru = client.add_face_with_options(add_face_request, runtime).status_code
        except TeaException as error:
            if error.statusCode == 400:
                ru = error.statusCode
            else:
                ru = None
        return ru

    @staticmethod
    def ListFaceEntities(db_name):
        client = Sample.create_client(getConfig("client.config", 'aliyun', 'AccessKeyID'),
                                      getConfig("client.config", 'aliyun', 'AccessKeySecret'))
        list_face_entities_request = facebody_20191230_models.ListFaceEntitiesRequest(db_name=db_name)
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            ru = client.list_face_entities_with_options(list_face_entities_request, runtime).body.data.to_map()[
                'Entities']
        except Exception as error:
            # 如有需要，请打印 error
            ru = UtilClient.assert_as_string(error)
        return ru

    @staticmethod
    def UpdateFaceEntity(db_name, entity_id, labels="学生"):
        client = Sample.create_client(getConfig("client.config", 'aliyun', 'AccessKeyID'),
                                      getConfig("client.config", 'aliyun', 'AccessKeySecret'))
        update_face_entity_request = facebody_20191230_models.UpdateFaceEntityRequest(
            entity_id=entity_id,
            labels=labels,
            db_name=db_name
        )
        runtime = util_models.RuntimeOptions()
        try:
            # 复制代码运行请自行打印 API 的返回值
            ru = client.update_face_entity_with_options(update_face_entity_request, runtime).status_code
        except Exception as error:
            # 如有需要，请打印 error
            ru = UtilClient.assert_as_string(error)
        return ru

    @staticmethod
    def SearchFace(db_name, image_path, limit=1):
        client = Sample.create_client(getConfig("client.config", 'aliyun', 'AccessKeyID'),
                                      getConfig("client.config", 'aliyun', 'AccessKeySecret'))
        file_utils = FileUtils(getConfig("client.config", 'aliyun', 'AccessKeyID'),
                               getConfig("client.config", 'aliyun', 'AccessKeySecret'))
        oss_url = file_utils.get_oss_url(image_path, "png", True)
        search_face_request = facebody_20191230_models.SearchFaceRequest(image_url=oss_url, db_name=db_name,
                                                                         limit=limit)
        runtime = util_models.RuntimeOptions()
        try:
            ru = client.search_face_with_options(search_face_request, runtime).body.data.to_map()['MatchList'][0][
                'FaceItems']
        except TeaException as error:
            if error.statusCode == 400:
                if error.data['Message'].find("input image not found face"):
                    ru = "input image not found face"
                else:
                    ru = None
            else:
                ru = None
        return ru

# print(Sample.CreateDelete_Face_Db('lunwen', operate.Create))
#print(Sample.AddDeleteFace_Entity(db_name='lunwen', entity_id='10003', entity_operate=operate.Delete))
# print(Sample.AddFace('lunwen', 'messigray.png', '27'))
# print(Sample.ListFaceDbs())
# print(Sample.UpdateFaceEntity('lunwen','wangzhuo'))
# print((Sample.ListFaceEntities("lunwen")))
# print(Sample.SearchFace(db_name='lunwen', image_path='messigray.png'))
